package com.monitor.secret;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ms.client.monitor.api.pojo.MsSecret;
import com.ms.client.monitor.api.service.ApiMsSecretService;
import com.ms.msclient.MsClientResponse;
import com.system.auth.AuthUtil;
import com.system.auth.model.AuthClient;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.handle.model.ResponseCode;

public class SecretUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(SecretUtil.class);

	public void init() {
		ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				LOGGER.info("初始更新密钥的线程:" + thread.getName());
				return thread;
			}
		});
		//线程，每隔30秒调用一次
		Runnable runnable = new Runnable() {
			public void run() {
				sync();
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, 10, 30, TimeUnit.SECONDS);
	}

	public static void sync() {
		ApiMsSecretService apiMsSecretService = FrameSpringBeanUtil.getBean(ApiMsSecretService.class);
		long start = System.currentTimeMillis();
		//Map<String, Object> paramsMap = new HashMap<String, Object>();
		MsClientResponse<MsSecret> response = apiMsSecretService.findUse();
		//ResponseFrame frame = MonitorUtil.post("/api/msSecret/findUse", paramsMap);
		if(ResponseCode.SUCC.getCode() == response.getCode().intValue()) {
			List<MsSecret> data = response.getBody();
			for (MsSecret ms : data) {
				AuthUtil.updateAuthClient(new AuthClient(ms.getCliId(), ms.getName(), ms.getDomain(), ms.getToken(),
						ms.getDomain()));
			}
			/*List<Map<String, Object>> data = frame.convertBody(HashMap.class);
				for (Map<String, Object> map : data) {
					String cliId = FrameMapUtil.getString(map, "cliId");
					String name = FrameMapUtil.getString(map, "name");
					String domain = FrameMapUtil.getString(map, "domain");
					String sercret = FrameMapUtil.getString(map, "token");
					AuthUtil.updateAuthClient(new AuthClient(cliId, name, domain, sercret, domain));
				}*/
		} else {
			LOGGER.error("获取密钥异常: " + FrameJsonUtil.toString(response));
		}
		long diff = System.currentTimeMillis() - start;
		if(diff > 100) {
			LOGGER.info("更新应用密钥 - 耗时： " + diff + "ms");
		}
	}
}
